package pers.zh.parking.mvp.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.Layer;
import pers.zh.parking.R;
import pers.zh.parking.amap.NaviInfoCallback;
import pers.zh.parking.common.Const;
import pers.zh.parking.data.entity.Car;
import pers.zh.parking.data.entity.ParkRecord;
import pers.zh.parking.data.entity.ParkingLot;
import pers.zh.parking.data.enums.RecordStatus;
import pers.zh.parking.di.component.DaggerReservationComponent;
import pers.zh.parking.mvp.contract.ReservationContract;
import pers.zh.parking.mvp.presenter.ReservationPresenter;
import pers.zh.parking.mvp.ui.adapter.CarsPopAdapter;
import pers.zh.parking.mvp.ui.adapter.ReservationAdapter;
import pers.zh.parking.utils.MyUtils;
import pers.zh.parking.utils.UIUtils;
import pers.zjc.commonlibs.util.ObjectUtils;
import pers.zjc.commonlibs.util.StringUtils;
import pers.zjc.commonlibs.util.ToastUtils;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class ReservationActivity extends BaseActivity<ReservationPresenter>
        implements ReservationContract.View, View.OnClickListener {

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.toolbar_left)
    RelativeLayout toolbarLeft;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl)
    SmartRefreshLayout rl;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private ReservationAdapter mAdapter;

    private LatLng curLoc = new LatLng(0, 0);

    private CarsPopAdapter carAdapter;
    private Layer layer;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerReservationComponent //如找不到该类,请编译一下项目
                                   .builder()
                                   .appComponent(appComponent)
                                   .view(this)
                                   .build()
                                   .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_reservation; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        curLoc = getIntent().getParcelableExtra(Const.Keys.KEY_CUR_LOCATION);
        initView();
        mPresenter.loadData();
    }

    private void initView() {
        tvTitle.setText("预约记录");
        mAdapter = new ReservationAdapter(new ArrayList<>());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        ivLeft.setOnClickListener(this);
        ivRight.setOnClickListener(this);
        rl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.loadData();
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ParkRecord item = mAdapter.getData().get(position);
                ParkingLot lot = item.getLot();
                switch (view.getId()) {
                    case R.id.btRight:
                        if (lot == null) {
                            return;
                        }
                        if (item.getStatusEnum() == RecordStatus.PARKING) {
                            // 点击支付
                            mPresenter.pay(item);
                        }
                        else {
                            // 点击导航
                            startNavi(item, lot);
                        }
                        break;
                    case R.id.btLeft:
                        mPresenter.cancel(item);
                        break;
                    default:
                        break;
                }

            }
        });
    }

    private void startNavi(ParkRecord item, ParkingLot lot) {
        if (curLoc.latitude == 0) {
            showMessage("未获取到当前位置");
        }
        MyUtils.startNavigate(ReservationActivity.this, curLoc,
                new LatLng(lot.getLatitude(), lot.getLongitude()), lot.getName(),
                new NaviInfoCallback(() -> UIUtils.createConfirmDialog(ReservationActivity.this, "是否到达目的地?", true,
                        (dialog, which) -> {
                            mPresenter.getCars(item);
                        }, (dialog, which) -> showMessage("请导航到该停车场进行泊车")).show()));
    }

    @Override
    public void showCarListDialog(List<Car> cars, ParkRecord item) {
        layer = AnyLayer.dialog(this)
                .contentView(R.layout.layout_car_dialog)
                .backgroundColorRes(R.color.white)
                .gravity(Gravity.CENTER)
                .cancelableOnTouchOutside(true)
                .cancelableOnClickKeyBack(true)
                .backgroundDimAmount(0.5f)
                .bindData(layer -> {
                    TextView tvTitle = layer.getView(R.id.tvTitle);
                    tvTitle.setText("请选择要停放的车辆");
                    RecyclerView rv = layer.getView(R.id.recyclerView);
                    rv.setLayoutManager(new LinearLayoutManager(ReservationActivity.this));
                    carAdapter = new CarsPopAdapter(cars);
                    rv.setAdapter(carAdapter);
                    carAdapter.setOnItemClickListener((adapter, view, position) -> {
                        layer.dismiss();
                        Car car = carAdapter.getData().get(position);
                        if (StringUtils.isEmpty(car.getCarNo())) {
                            showMessage("该车辆没有车牌信息，请完善");
                            return;
                        }
                        item.setCarNo(car.getCarNo());
                        mPresenter.startPark(item);
                    });
                });
        layer.show();

    }

    @Override
    public void showLoading() {
        rl.autoRefresh();
    }

    @Override
    public void hideLoading() {
        rl.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastUtils.showShort(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivLeft:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void showList(List<ParkRecord> data) {
        if (ObjectUtils.isEmpty(data)) {
            mAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
            return;
        }
        mAdapter.replaceData(data);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void updateSuccess(ParkRecord record, String msg, int type) {
        showMessage(msg);
//        mAdapter.getData().forEach(item -> {
//            if (item.getRecordId() == record.getRecordId()) {
//                switch (type) {
//                    case ReservationPresenter.TYPE_CACEL:
//                        item.setStatus(RecordStatus.CANCEL.getStatus());
//                        break;
//                    case ReservationPresenter.TYPE_PARK:
//                        item.setStatus(RecordStatus.PARKING.getStatus());
//                        break;
//                    case ReservationPresenter.TYPE_PAY:
//                        item.setStatus(RecordStatus.LEAVED.getStatus());
//                        break;
//                    default:
//                        break;
//                }
//            }
//        });
//        mAdapter.notifyDataSetChanged();
        mPresenter.loadData();
        if (type == ReservationPresenter.TYPE_PARK) {
            launchActivity(new Intent(ReservationActivity.this, ParkActivity.class));
            finish();
        }
    }

}
